#============================================================
#	Collsion Wrapper
#============================================================
#  碰撞装饰器器
#============================================================
# * 调用个 Wrapper 的 disabled 方法即可使添加的碰撞节点失效一段时间
#============================================================
# @datetime: 2022-4-17 14:43:04
#============================================================
class_name CollisionWrapper
extends RunnableWrapper


func _init(host).(host):
	pass
	__interval_timer__ = create_timer(false)
	__disabled_timer__ = create_timer(false)
	__disabled_timer__.connect("timeout", self, "_disabled_timer_timeout")


#============================================================
#   自定义
#============================================================
signal disabled_changed(value)
signal refreshed


# 碰撞节点列表
var __collisions__ : Array = []
# 使用间隔时间
var __interval_time__ : float = 0.2
var __interval_timer__ : Timer
# 失效时间
var __disabled_time__ : float = 0.1
var __disabled_timer__ : Timer


func _set_disabled(value: bool):
	for collision in __collisions__:
		collision.set_deferred("disabled", value)
	emit_signal("disabled_changed", value)

func is_enabled() -> bool:
	return get_interval_timer().time_left <= 0

func get_interval_timer() -> Timer:
	if __interval_timer__ == null:
		__interval_timer__ = create_timer(true)
	return __interval_timer__

func get_disabled_timer() -> Timer:
	if __disabled_timer__ == null:
		__disabled_timer__ = create_timer(true)
		__disabled_timer__.connect("timeout", self, "_disabled_timer_timeout")
	return __disabled_timer__

##  设置使用间隔间隔
func set_interval(value: float) -> CollisionWrapper:
	__interval_time__ = max(0.02, value)
	return self

##  设置碰撞不可用时间 
func set_disabled_time(value: float) -> CollisionWrapper:
	__disabled_time__ = max(0.02, value)
	return self

##  添加碰撞
## @collision  
func add_collision(collision: CollisionShape2D) -> CollisionWrapper:
	__collisions__.append(collision)
	return self


##  失效
func disabled():
	if is_enabled():
		# 可再次使用用倒计时
		get_interval_timer().start(__interval_time__)
		# 失效
		_set_disabled(true)
		# 开始失效持续时间计时器
		get_disabled_timer().start(__disabled_time__)


#(override)
func run(data=null):
	disabled()


func _disabled_timer_timeout():
	_set_disabled(false)
	emit_signal("refreshed")

